<template>
  <a-modal
    :title="title"
    :width="800"
    :visible="visible"
    :maskClosable="false"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel"
  >
    <template slot="footer">
      <a-button type="primary" @click="handleOk">暂存</a-button>
      <a-button type="primary" @click="submit">提交</a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <div style="overflow-y: scroll; height: 500px">
        <avue-form v-if="visible" class="preview-form" :option="widgetFormPreview" @submit="submit" v-model="model">
        </avue-form>
        <a-tabs>
          <a-tab-pane tab="附件">
            <template v-if="fileTitle">
              <a-upload
                :action="uploadAction"
                :headers="headers"
                :showUploadList="false"
                :multiple="true"
                @change="handleChange"
              >
                <span style="color: red" v-if="fileRequired">*</span
                ><span style="font-weight: 700">{{ fileTitle }}：</span>
                <a-button>
                  <a-icon type="upload" />
                  上传
                </a-button>
              </a-upload>
              <div>
                <a-list itemLayout="horizontal" :dataSource="sysFileList">
                  <a-list-item slot="renderItem" slot-scope="item">
                    <a @click="deleteFile(item.fileId)" slot="actions">删除</a>
                    <a-list-item-meta description>
                      <a style="color: #1890ff" slot="title" :href="buildFilePath(item.filePath)">{{
                        item.originalName
                      }}</a>
                    </a-list-item-meta>
                  </a-list-item>
                </a-list>
              </div>
            </template>
            <template v-if="fileImgTitle">
              <div>
                <span v-if="fileImgRequired" style="color: red">*</span
                ><span style="font-weight: 700">{{ fileImgTitle }}：</span>
                <div>
                  <a-upload
                    v-if="imgLoading"
                    :action="uploadImgAction"
                    :headers="headers"
                    :multiple="true"
                    list-type="picture-card"
                    accept=".jpg, .png, .jpeg, .bmp"
                    :file-list="sysImgFileShowList.showList"
                    @preview="(file) => handlePreview(file)"
                    :remove="(e) => onRemove(e)"
                    @change="(file) => handleImgChange(file)"
                    class="uploadButtonStyle"
                  >
                    <a-button>
                      <a-icon type="upload" />
                      上传
                    </a-button>
                  </a-upload>
                </div>
              </div>
            </template>
            <div class="outer_box" v-if="previewVisible">
              <previewPicture
                @cancel="handleImgCancel"
                :fileList="sysImgFileShowList"
                :fileNum="previewNum"
              ></previewPicture>
            </div>
          </a-tab-pane>
        </a-tabs>
      </div>
    </a-spin>
  </a-modal>
</template>

<script>
import { postAction, putAction, getAction } from '@/api/manage'
import Vue from 'vue'
import { REDIS_INDEX, SOURCE_NAME } from '@/store/mutation-types'
import PreviewPicture from '@/components/tools/PreviewPicture.vue'
import {errorBack} from '@/components/packages/toolFormUtil'

export default {
  name: 'TpFormDataStructureModal',
  components: { PreviewPicture },
  data() {
    return {
      title: '操作',
      visible: false,
      model: {},
      widgetFormPreview: {},
      code: '', //表单编码
      confirmLoading: false,
      type: '', //新增还是编辑还是详情
      id: '', //表单数据ID
      url: {
        add: '/form/tpFormDataStructure/add',
        edit: '/form/tpFormDataStructure/edit',
        queryByCode: '/form/tpFormStructure/queryByCode',
        queryStructureById: '/form/tpFormDataStructure/queryStructureById',
        handleSubmit: '/form/tpFormDataStructure/handleSubmit',
        fileUpload: window._CONFIG['domianURL'] + '/common/file/uploadImg?parenPath=contract&uploadType=5',
        fileUploadImg: window._CONFIG['domianURL'] + '/common/file/uploadImg?parenPath=contract&uploadType=0',
        queryByFormCode: '/form/tpFormInfo/queryByFormCode',
      },
      //附件上传
      sysFileList: [],
      sysImgFileList: [], //图片
      sysImgFileShowList: { showList: [] }, //回显的图片数组
      imgLoading: true,
      previewVisible: false, //图片预览显隐
      previewNum: 0,
      fileRequired: true,
      fileImgRequired: true,
      fileTitle: '',
      fileImgTitle: '',
    }
  },
  computed: {
    uploadAction: function () {
      return this.url.fileUpload
    },
    uploadImgAction: function () {
      return this.url.fileUploadImg
    },
  },
  created() {
    this.headers = {
      sourceName: Vue.ls.get(SOURCE_NAME),
      redisIndex: Vue.ls.get(REDIS_INDEX),
    }
  },
  methods: {
    //图片预览关闭
    handleImgCancel() {
      this.previewVisible = false
    },
    //图片预览
    handlePreview(file) {
      let id = file.response ? file.response.result.id : file.uid
      for (let index in this.sysImgFileShowList.showList) {
        let uid = this.sysImgFileShowList.showList[index].response
          ? this.sysImgFileShowList.showList[index].response.result.id
          : this.sysImgFileShowList.showList[index].uid
        if (id == uid) {
          this.previewNum = index
        }
      }
      this.previewVisible = true
    },
    //图片删除
    onRemove(result) {
      let id = result.response ? result.response.result.id : result.uid
      this.sysImgFileList = this.sysImgFileList.filter((item) => item.fileId != id)
      this.sysImgFileShowList.showList = this.sysImgFileShowList.showList.filter((item) => item.uid != id)
    },
    //上传完文件，往enclosureList传值，用来展示
    handleChange(info) {
      this.buildFileTemp(info, 'file')
    },
    //构造文件数组
    buildFileTemp(info, type) {
      if (info.file.status === 'done') {
        if (info.file.response && info.file.response.success) {
          let temp = {}
          temp.originalName = info.file.response.result.originalName
          temp.fileName = info.file.response.result.fileName.split('.')[1]
          temp.filePath = info.file.response.result.filePath
          temp.fileId = info.file.response.result.id
          temp.fileType = info.file.response.result.fileType
          if (type == 'img') {
            this.sysImgFileList.push(temp)
          } else {
            this.sysFileList.push(temp)
          }
        }
      }
    },
    //上传完文件，往enclosureList传值，用来展示
    handleImgChange(info) {
      this.buildFileTemp(info, 'img')
      let { fileList } = info
      this.sysImgFileShowList.showList = [...fileList]
    },
    //删除上传的文件
    deleteFile(fileId) {
      this.sysFileList = this.sysFileList.filter((item) => item.fileId != fileId)
    },
    buildFilePath(filePath) {
      return window._CONFIG['staticDomainURL'] + '/' + filePath
    },
    //初始化附件是否必填
    initFileRequired() {
      this.fileTitle = ''
      this.fileImgTitle = ''
      getAction(this.url.queryByFormCode, { code: this.code }).then((res) => {
        if (res.success) {
          //解析描述字段
          if (res.result.formDescribe) {
            let tempArr = res.result.formDescribe.split('\n')
            if (tempArr && tempArr.length > 0) {
              for (let index in tempArr) {
                if (tempArr[index].indexOf('附件') > -1) {
                  this.fileTitle = tempArr[index].split('：')[0]
                  this.fileRequired = tempArr[index].split('：')[1] == '必填' ? true : false
                }
                if (tempArr[index].indexOf('图片') > -1) {
                  this.fileImgTitle = tempArr[index].split('：')[0]
                  this.fileImgRequired = tempArr[index].split('：')[1] == '必填' ? true : false
                }
              }
            }
            console.log(res.result.formDescribe.split('\n'))
          }
        }
      })
    },
    //新增初始化
    add(code) {
      getAction(this.url.queryByCode, { code: code }).then((res) => {
        if (res.success) {
          this.code = code
          this.type = 'add'
          //  新增页面按钮编辑与隐藏
          let widgetFormPreview = JSON.parse(res.result.formStructure)
          widgetFormPreview.menuBtn = false
          this.widgetFormPreview = widgetFormPreview
          this.visible = true
          this.$nextTick(() => {
            this.initFileRequired()
          })
        }
      })
    },
    //编辑初始化
    edit(id) {
      getAction(this.url.queryStructureById, { id: id }).then((res) => {
        if (res.success) {
          this.type = 'edit'
          this.model = JSON.parse(res.result.dataStructure)
          this.id = id
          this.code = res.result.formCode
          this.initFile(res.result.sysFileList)
          this.widgetFormPreview = JSON.parse(res.result.formStructure)
          this.visible = true
          this.$nextTick(() => {
            this.initFileRequired()
          })
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    //初始化文件
    initFile(fileList) {
      //附件
      this.sysFileList = fileList.filter((item) => item.fileType == '5')
      //图片
      this.sysImgFileList = fileList.filter((item) => item.fileType == '0')
      //图片的预览数据
      this.sysImgFileShowList.showList = []
      if (this.sysImgFileList) {
        for (let index in this.sysImgFileList) {
          let showTemp = {}
          showTemp.name = this.sysImgFileList[index].originalName
          showTemp.uid = this.sysImgFileList[index].fileId
          showTemp.url = this.buildFilePath(this.sysImgFileList[index].filePath)
          showTemp.originalImage = showTemp.url
          this.sysImgFileShowList.showList.push(showTemp)
        }
      }
      this.imgLoading = true
    },
    close() {
      this.widgetFormPreview = {}
      this.sysFileList = []
      this.sysImgFileList = []
      this.sysImgFileShowList = []
      this.model = {}
      this.visible = false
    },
    handleCancel() {
      this.close()
    },
    //暂存
    handleOk(val) {
      let msg = errorBack(this.widgetFormPreview,this.model)
      if(msg.length>0){
        for(let index in msg){
          this.$message.warning((msg[index].index ? '第' + (parseInt(msg[index].index)+1) + '条的'  : '') + msg[index].text + '不能为空')
          return false
        }
      }
      if (this.widgetFormPreview.column) {
        if (this.fileRequired && (!this.sysFileList || this.sysFileList.length == 0)) {
          that.$message.warning('请选择附件')
          ifSuccess = false
          this.$emit('errback')
          reject(0)
          return false
        }
        if (this.fileImgRequired && (!this.sysImgFileList || this.sysImgFileList.length == 0)) {
          that.$message.warning('请选择图片')
          ifSuccess = false
          this.$emit('errback')
          reject(0)
          return false
        }
        //新增
        if (this.type == 'add') {
          postAction(this.url.add, {
            formCode: this.code,
            dataStructure: JSON.stringify(this.model),
            sysFileList: this.sysFileList.concat(this.sysImgFileList),
          }).then((res) => {
            if (res.success) {
              this.$message.success('添加成功！')
              this.handleCancel()
              this.$emit('ok')
            }
          })
        }

        //编辑
        if (this.type == 'edit') {
          putAction(this.url.edit, { id: this.id, dataStructure: JSON.stringify(this.model) }).then((res) => {
            if (res.success) {
              this.$message.success('编辑成功！')
              this.handleCancel()
              this.$emit('ok')
            }
          })
        }
      }
    },
    //提交
    submit() {
      if (this.widgetFormPreview.column) {
        if (this.fileRequired && (!this.sysFileList || this.sysFileList.length == 0)) {
          that.$message.warning('请选择附件')
          ifSuccess = false
          this.$emit('errback')
          reject(0)
          return false
        }
        if (this.fileImgRequired && (!this.sysImgFileList || this.sysImgFileList.length == 0)) {
          that.$message.warning('请选择图片')
          ifSuccess = false
          this.$emit('errback')
          reject(0)
          return false
        }
        //新增
        if (this.type == 'add') {
          postAction(this.url.add, {
            formCode: this.code,
            dataStructure: JSON.stringify(this.model),
            sysFileList: this.sysFileList.concat(this.sysImgFileList),
          }).then((res) => {
            if (res.success) {
              getAction(this.url.handleSubmit, { id: res.result }).then((res) => {
                if (res.success) {
                  this.$message.success(res.message)
                  this.handleCancel()
                  this.$emit('ok')
                } else {
                  this.$message.warning(res.message)
                  this.$emit('ok')
                }
              })
            }
          })
        }
        //编辑
        if (this.type == 'edit') {
          putAction(this.url.edit, { id: this.id, dataStructure: JSON.stringify(this.model),isSubmit:true }).then((res) => {
            if (res.success) {
              this.$message.success(res.message)
              this.handleCancel()
              this.$emit('ok')
            } else {
              this.$message.warning(res.message)
              this.$emit('ok')
            }
              // getAction(this.url.handleSubmit, { id: this.id }).then((res) => {
              //   if (res.success) {
              //     this.$message.success(res.message)
              //     this.handleCancel()
              //     this.$emit('ok')
              //   } else {
              //     this.$message.warning(res.message)
              //     this.$emit('ok')
              //   }
              // })
          })
        }
      }
    },
  },
}
</script>

<style lang="less" scoped>
// @import '../../../components/packages/styles/index.scss';
// @import '../../../components/packages/styles/index.scss';
/deep/.uploadButtonStyle{
  // 图片预览删除按钮样式Start
  .ant-upload-list-picture-card-container{
    &:hover{
      .ant-upload-list-item-name{
        display: none!important;
      }
    }
  }
  .ant-upload-list-picture-card .ant-upload-list-item-info::before{
    background-color: rgba(#000,0.1);
  }
  .ant-upload-list-item-actions{
    width:calc(100% - 16px);
    height:calc(100% - 16px);
    //预览按钮
    a{
      height: 100%;
      background-color: #1075D34C;
      display: block;
      &::after{
        content: "查看大图";
        color: white;
        display: flex;
        align-items: center;
        justify-content: center;
        height: 100%;
      }
      i{
        display: none;
      }
    }
    //删除按钮
    .anticon-delete{
      /* font-size: 18px; */
      display: block;
      width: 22px;
      height: 22px;
      border-radius: 50%;
      background-color: rgb(255 0 0);
      margin: 0;
      position: absolute;
      top: -14px;
      right: -14px;
      background-image:url("../../../assets/image/upload_delete.png");
      background-size: contain;
      svg{
        display: none;
      }
    }
  }
  // 图片预览删除按钮样式End
}
</style>
<style scoped src="../../../components/packages/styles/index1.css">
</style>